<template>
  <a-select
    v-model:model-value="state.active"
    clearable
  >
    <a-option v-for="item in state.list" :key="item.value" :label="item.label" :value="item.value"></a-option>
  </a-select>
</template>

<script lang="ts" setup>

import { onMounted, reactive, watch } from "vue";
import { CommonApi } from "@/api/system/common.api";
import {AttachMore} from "~/icesoft/utils/service/types";

interface Props {
  params: AttachMore;
  modelValue?: string;
  autoSelect?: boolean;
}

const props = defineProps<Props>();

const { modelValue, params, autoSelect } = reactive(props);

const emits = defineEmits(["update:modelValue"]);
const commonApi = new CommonApi();
const state = reactive<{
  list: any[],
  active: string,
}>({
  list: [],
  active: "",
});

function init() {
  commonApi.attachMore([params]).then(res => {
    if (res.ok) {
      state.list = res.data[`${params.target.toLowerCase().replace(/\_(\w)/g, (_, letter) => letter.toUpperCase())}Options`];
      if (autoSelect) {
        if (!modelValue) {
          state.active = (state.list[0] as any).value;
        }
      }
    }
  });
}

watch(() => state.active, value => {
  emits("update:modelValue", value);
});

watch(props, value => {
  if (value.modelValue) {
    state.active = value.modelValue;
  }
}, { immediate: true });

onMounted(() => {
  init();
});

</script>

<style lang="scss" scoped>
.attachMore-button {
  .active {

  }
}
</style>
